package com.taotao.frame.util;

import com.taotao.frame.common.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

/**
 * @author
 * @description Base64加密解密类
 * @date 2019/4/18 15:09
 */
@Slf4j
public class Base64Util {
    private Base64Util() {
    }


    /**
     * base64加密
     *
     * @param plainText 待加密字符
     * @return 加密结果
     */
    public static String encode(String plainText) {

        String result = null;

        try {
            byte[] b = plainText.getBytes();
            Base64 base64 = new Base64();
            b = base64.encode(b);
            result = new String(b, Constant.PROJECT_DEFAULT_ENCODING);
        } catch (Exception e) {
            log.error(">>>> getFromBase64() msg={}, plainText={} <<<<", ExceptionUtils.getStackTrace(e), plainText);
            e.printStackTrace();
        }
        return result;
    }


    /**
     * base64解密
     *
     * @param base64Str 待解密字符
     * @return 解密结果
     */
    public static String decode(String base64Str) {
        String result = null;
        if (StringUtils.isBlank(base64Str)) {
            return null;
        }
        try {
            Base64 base64 = new Base64();
            byte[] b = base64.decode(base64Str.getBytes(Constant.PROJECT_DEFAULT_ENCODING));
            result = new String(b, Constant.PROJECT_DEFAULT_ENCODING);

        } catch (Exception e) {
            log.error(">>>> getBase64() msg={}, base64Str={} <<<<", e.getMessage(), base64Str);
            e.printStackTrace();
        }
        return result;
    }
}

